package com.text.controller;

import com.text.entity.Course;
import com.text.entity.StudentAndCourse;
import com.text.entity.Student;
import com.text.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/students")
public class StudentController {

    @Autowired
    private StudentService studentService;

    // 添加学生及其课程
    @PostMapping("/add")
    public ResponseEntity<String> addStudentWithCourses(@RequestParam String studentId, @RequestParam Set<String> courseIds) {
        // 从数据库获取学生信息
        Student student = studentService.getStudent(studentId);
        if (student == null) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Student not found with ID: " + studentId);
        }

        // 添加学生和课程
        studentService.addStudentWithCourses(student, courseIds);

        return ResponseEntity.ok("Student and courses added successfully!");
    }

    // 获取学生信息
    @GetMapping("/{id}")
    public ResponseEntity<Student> getStudent(@PathVariable String id) {
        Student student = studentService.getStudent(id);
        if (student == null) {
            return ResponseEntity.notFound().build(); // 如果学生不存在，返回 404
        }
        return ResponseEntity.ok(student); // 返回学生信息
    }

    // 获取所有学生
    @GetMapping
    public ResponseEntity<List<Student>> getAllStudents() {
        List<Student> students = studentService.getAllStudents();
        return ResponseEntity.ok(students); // 返回所有学生信息
    }

    // 更新学生信息
    @PutMapping("/{id}")
    public ResponseEntity<String> updateStudent(@PathVariable String id, @RequestBody Student updatedStudent) {
        boolean updated = studentService.updateStudent(id, updatedStudent);
        if (updated) {
            return ResponseEntity.ok("Student updated successfully!");
        } else {
            return ResponseEntity.notFound().build(); // 如果学生不存在，返回 404
        }
    }

    // 删除学生
    @DeleteMapping("/{id}")
    public ResponseEntity<String> deleteStudent(@PathVariable String id) {
        boolean deleted = studentService.deleteStudent(id);
        if (deleted) {
            return ResponseEntity.ok("Student deleted successfully!");
        } else {
            return ResponseEntity.notFound().build(); // 如果学生不存在，返回 404
        }
    }
}